﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Gta.Common;

public static partial class GpuHudEntityHelper
{
    /// <summary>
    /// 根据EntityType和id获取对应的GpuHudAsset
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private static GpuHudAsset LoadAssetById(GpuHudEntityType entityType,int id)
    {
        GpuHudFacade curFacade = GpuHudFacade.GpuFacade;
        GpuHudAsset tempAsset = curFacade.GetAsset(entityType, id);

        if (tempAsset == null)
        {
            string luaFunc = GetLuaFunc(entityType);
            ResidentHandler.Inst.GetFunction(luaFunc).Action<int, Action<object>>(id, (object obj) =>
            {
                tempAsset = obj as GpuHudAsset;
                if (tempAsset != null)
                {
                    OnLoadFinish(entityType,id, tempAsset);
                }
            });
        }

        return tempAsset;
    }
    /// <summary>
    /// 加载资源后处理,用于记录资源占用情况,当资源计数器为0时,卸载资源
    /// </summary>
    /// <param name="id"></param>
    /// <param name="asset"></param>
    private static void OnLoadFinish(GpuHudEntityType entityType,int id, GpuHudAsset asset)
    {
        GpuHudFacade curFacade = GpuHudFacade.GpuFacade;
        curFacade.OnAssetInit(entityType, id, asset);
    }

    /// <summary>
    /// 获取GpuHud实体,同时初始化,asset计数器+1
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public static T GetHudEntity<T>(GpuHudEntityType entityType,int id,int defaultId) where T : GpuHudEntityBase,new()
    {
        string luaFunc = GetLuaFunc(entityType);
        if (luaFunc == "") return null;
        
        GpuHudEntityBase entity = null;
        
        GpuHudAsset asset = LoadAssetById(entityType, id);
        if(asset == null && defaultId != -1)
        {
            asset = LoadAssetById(entityType, defaultId);
        }
        
        //不使用T(),防止反射
        switch (entityType)
        {
            case GpuHudEntityType.FlyText:
                entity = new GpuFlyTextEntity();
                break;
            case GpuHudEntityType.PlayerName:
                entity = new GpuPlayerNameEntity();
                break;
            default:
                entity = null;
                break;
        }
        if(entity != null)
        {
            entity.OnInit(asset);
            return entity as T;
        }
        return null;
    }

    private static string GetLuaFunc(GpuHudEntityType entityType)
    {
        switch (entityType)
        {
            case GpuHudEntityType.FlyText:
                return FlyTextLuaFunc;
            case GpuHudEntityType.PlayerName:
                return PlayerNameLuaFunc;
        }
        return "";
    }

    public static string FlyTextLuaFunc    = "L_GpuHudLuaFunction.LoadFlyTextById";
    public static string PlayerNameLuaFunc = "L_GpuHudLuaFunction.LoadPlayerNameById";
}
